package com.atguigu.tingshu.order.api;

import com.atguigu.tingshu.common.login.anotation.NeedLogin;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import kotlin.ResultKt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "订单管理")
@RestController
@RequestMapping("api/order/orderInfo")
@SuppressWarnings({"unchecked", "rawtypes"})
public class OrderInfoApiController {

	@Autowired
	private OrderInfoService orderInfoService;



	//Request URL: http://localhost:8500/api/order/orderInfo/trade
	/**
	 * 用户购买音频或专辑的订单结算页面展示
	 * @param tradeVo 购买结算信息
	 * @return 结算数据
	 */
	@PostMapping("/trade")
	@Operation(summary = "订单结算页面")
	@NeedLogin
	public Result trade(@RequestBody TradeVo tradeVo){
		OrderInfoVo orderInfoVo = orderInfoService.trade(tradeVo);
		List<Object> exitItemIds = orderInfoVo.getExitItemIds();
		if (!CollectionUtils.isEmpty(exitItemIds)){
			return Result.build(exitItemIds, 301, "当前用户购买的音频列表存在已支付项");
		}
		return Result.ok(orderInfoVo);
	}

	//Request URL: http://localhost:8500/api/order/orderInfo/submitOrder
	/**
	 * 用户提交订单
	 * @param orderInfoVo 订单数据
	 * @return
	 */
	@PostMapping("/submitOrder")
	@Operation(summary = "用户提交订单")
	@NeedLogin
	public Result submitOrder(@RequestBody OrderInfoVo orderInfoVo){
		Map<String, Object> map = orderInfoService.submitOrder(orderInfoVo);
		return Result.ok(map);
	}

	//Request URL: http://localhost:8500/api/order/orderInfo/getOrderInfo/UFqSltyuFFXEMMp
	/**
	 * 根据订单号获取该订单详情
	 * @param orderNo 订单号
	 * @return 订单详情
	 */
	@GetMapping("/getOrderInfo/{orderNo}")
	@NeedLogin
	@Operation(summary = "根据订单号获取当前用户的订单详情")
	public Result getOrderInfo(@PathVariable String orderNo){
		OrderInfo result = orderInfoService.getOrderInfoAndDetail(orderNo);
		return Result.ok(result);
	}


	//Request URL: http://localhost:8500/api/order/orderInfo/findUserPage/1/10

	/**
	 * 分页查询用户订单列表
	 * @param pageNum 页码
	 * @param pageSize 每页记录数
	 * @return 订单列表
	 */
	@GetMapping("/findUserPage/{pageNum}/{pageSize}")
	@NeedLogin
	@Operation(summary = "分页查询当前用户的订单列表")
	public Result findUserPage(@PathVariable Long pageNum,
							   @PathVariable Long pageSize){
		IPage<OrderInfo> page = new Page<>(pageNum,pageSize);
		page = orderInfoService.findUserPage(page, AuthContextHolder.getUserId());
		return Result.ok(page);
	}
}

